package pl.smath.regex.tree.vertexes;

import java.util.HashMap;

import pl.smath.regex.exceptions.ParseError;
import pl.smath.regex.tree.Parser;

public class SumVertex extends Vertex {

	private String iterator = "";
	private ConstVertex start;
	private ConstVertex end;
	private Vertex inside;
	
	/**
	 *  Assuming that parse is an expression in format: "Sum{range}{expression}"
	 */
	public SumVertex(String parse) throws ParseError {
		int from = parse.indexOf("{");
		int to = parse.indexOf("}");
		String range = parse.substring(from+1, to);
		from = parse.indexOf("{", to);
		to = parse.indexOf("}", from);
		String exp = parse.substring(from+1, to);
		
		to = range.indexOf(":");
		iterator = range.substring(0, to);
		if(!iterator.matches("[a-z]")) 
			throw new ParseError("Invalid sum iterator format.");
		
		from = to;
		to = range.indexOf(",");
		start = new ConstVertex(range.substring(from+1, to));
		from = range.indexOf(":", to);
		end = new ConstVertex(range.substring(from+1));
		
		HashMap<String, String> special = new HashMap<String, String>();
		special.put(iterator, "SUM_ITERATOR");
		
		Parser parser = new Parser(special);
		inside = parser.parse(exp);
		
	}

	public boolean checkIndex(int i) {
		ConstVertex index = new ConstVertex(i);
		if (start.compareTo(index) <= 0 && index.compareTo(end) <= 0) return true;
		return false;
	}
	

	public String serialize() {
		return "SUM[" + iterator + "," + start.serialize() + "," + end.serialize() + "," + inside.serialize() + "]";
	}


	public Vertex getInside() {
		return inside;
	}
	
	public String getIter() {
		return iterator;
	}
}
